// -----------------------------------------------------------------------
//  <copyright file="DeleteOrganizationCommand.cs" company="LiuliuSoft">
//      Copyright (c) 2022-2024 DaprPlus. All rights reserved.
//  </copyright>
//  <site>https://dapr.plus</site>
//  <last-editor>郭明锋</last-editor>
//  <last-date>2024/12/10 14:36:07</last-date>
// -----------------------------------------------------------------------

using DaprPlus.Identity.Domain.Entities;

using DaprPlus.Identity.Application.Identity.Organizations.Specs;


namespace DaprPlus.Identity.Application.Identity.Organizations.Commands;

[AuthConfig(typeof(Organization), ResourceAccessType.RoleLimit, "Delete")]
public class DeleteOrganizationCommand : IRequest<ApiResult>, ICommand
{
    public DeleteOrganizationCommand(long[] ids)
    {
        Ids = ids;
    }

    public long[] Ids { get; }
}

public class DeleteOrganizationCommandHandler(IRepository<Organization> repository)
    : IRequestHandler<DeleteOrganizationCommand, ApiResult>
{
    public async Task<ApiResult> Handle(DeleteOrganizationCommand request, CancellationToken cancellationToken)
    {
        foreach (var id in request.Ids)
        {
            var entity = await repository.FindAsync(id, cancellationToken);
            if (entity == null)
            {
                return new ApiResult(ApiResultType.Error, $"编号为 {id} 的组织机构不存在");
            }

            // 检查是否存在子组织机构
            var spec = new OrganizationByParentIdSpec(id);
            var hasChildren = await repository.AnyAsync(spec, cancellationToken);
            if (hasChildren)
            {
                return new ApiResult(ApiResultType.Error, $"组织机构 {entity.Name} 存在子组织机构，不能删除");
            }

            await repository.DeleteAsync(entity, cancellationToken);
        }

        return new ApiResult(ApiResultType.Success);
    }
}

